package com.gnerv.pabu.plugin.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class VelocityUtils {

    private static final Properties INIT_PROP;

    static {
        INIT_PROP = new Properties();
        // 修复部分用户的velocity日志记录无权访问velocity.log文件问题
        INIT_PROP.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
        INIT_PROP.setProperty("runtime.log.logsystem.log4j.logger", "velocity");
    }

    private VelocityUtils() {
        throw new UnsupportedOperationException();
    }

    public static String generate(String templateCode, Map<String, Object> map) {
        VelocityEngine velocityEngine = new VelocityEngine(INIT_PROP);
        VelocityContext velocityContext = new VelocityContext();
        if (map != null) {
            map.forEach(velocityContext::put);
        }
        StringWriter stringWriter = new StringWriter();
        try {
            velocityEngine.evaluate(velocityContext, stringWriter, "Velocity Code Generate", templateCode);
        } catch (Exception e) {
            log.info("", e);
        }
        return stringWriter.toString().replace("\r", "");
    }

}
